// 全局变量
let records = [];
let currentPage = 1;
const recordsPerPage = 10;
let currentRecordId = null;
let trendChart = null;
let pieChart = null;


// DOM 元素
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');
const addRecordBtn = document.getElementById('addRecordBtn');
const recordModal = document.getElementById('recordModal');
const closeModal = document.getElementById('closeModal');
const recordForm = document.getElementById('recordForm');
const recordsTableBody = document.getElementById('recordsTableBody');
const searchInput = document.getElementById('searchInput');
const filterSelect = document.getElementById('filterSelect');
const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage');
const showingRange = document.getElementById('showingRange');
const totalCount = document.getElementById('totalCount');
const totalRecordsEl = document.getElementById('totalRecords');
const totalAmountEl = document.getElementById('totalAmount');
const lastUpdatedEl = document.getElementById('lastUpdated');
const deleteModal = document.getElementById('deleteModal');
const cancelDelete = document.getElementById('cancelDelete');
const confirmDelete = document.getElementById('confirmDelete');
const notification = document.getElementById('notification');
const notificationIcon = document.getElementById('notificationIcon');
const notificationMessage = document.getElementById('notificationMessage');
const relationStats = document.getElementById('relationStats');
const loadingIndicator = document.getElementById('loadingIndicator');
const logoffBtn = document.getElementById('logoffBtn');  logoffBtn

// 预览开始============================= 1
// 获取预览元素
const previewName = document.getElementById('previewName');
const previewAmount = document.getElementById('previewAmount');
const previewType = document.getElementById('previewType');

// 预设金额选项
const presetAmounts = [500, 800, 1000, 1200, 1600, 1800, 2000, 5000, 8000];
// 获取容器元素
const radioContainer = document.getElementById('radioContainer');
// 生成预设金额选项
presetAmounts.forEach(amount => {
    const label = document.createElement('label');
    label.className = 'inline-flex items-center';
    label.innerHTML = `
        <input type="radio" name="amountOption" value="${amount}" class="text-primary focus:ring-primary/50 border-gray-300 h-4 w-4">
        <span class="ml-2 text-base">${amount}</span>
    `;
    radioContainer.appendChild(label);
});

// 添加"其他"选项
const customLabel = document.createElement('label');
customLabel.className = 'inline-flex items-center';
customLabel.innerHTML = `
    <input type="radio" name="amountOption" value="custom" class="text-primary focus:ring-primary/50 border-gray-300 h-4 w-4">
    <span class="ml-2 text-base">其他</span>
`;

radioContainer.appendChild(customLabel);

// 获取表单元素
const nameInput = document.getElementById('name');
const amountRadios = document.querySelectorAll('input[name="amountOption"]');
const customAmountInput = document.getElementById('customAmount');
const typeRadios = document.querySelectorAll('input[name="type"]');
// 更新姓名预览
nameInput.addEventListener('input', () => {
    previewName.textContent = nameInput.value || '-';
});

// 更新金额预览
function updateAmountPreview() {
    let amount = 0;
    let selectedRadio = document.querySelector('input[name="amountOption"]:checked');
    
    if (selectedRadio.value === 'custom') {
        amount = parseFloat(customAmountInput.value) || 0;
    } else {
        amount = parseFloat(selectedRadio.value) || 0;
    }
    
    previewAmount.textContent = `¥${amount.toFixed(2)}`;
}

// 监听金额选项变化
amountRadios.forEach(radio => {
    radio.addEventListener('change', updateAmountPreview);
});

// 监听自定义金额输入变化
customAmountInput.addEventListener('input', updateAmountPreview);

// 更新类型预览
function updateTypePreview() {
    const selectedType = document.querySelector('input[name="type"]:checked').value;
    
    if (selectedType === 'in') {
        previewType.innerHTML = '<span class="px-3 py-1 bg-green-100 text-green-800 rounded-full">收入</span>';
        previewAmount.className = 'text-4xl font-bold text-green-600';
    } else {
        previewType.innerHTML = '<span class="px-3 py-1 bg-red-100 text-red-800 rounded-full">支出</span>';
        previewAmount.className = 'text-4xl font-bold text-red-600';
    }
}


// 监听类型选项变化
typeRadios.forEach(radio => {
    radio.addEventListener('change', updateTypePreview);
});
// 预览结束============================= 1

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 设置默认日期为今天
    document.getElementById('date').valueAsDate = new Date();
    
    // 从服务器加载记录
    fetchRecords();
    
    // 初始化图表
    initCharts();
    
    // 事件监听
    mobileMenuBtn.addEventListener('click', toggleMobileMenu);
    addRecordBtn.addEventListener('click', openAddModal);
    closeModal.addEventListener('click', closeRecordModal);
    recordForm.addEventListener('submit', handleFormSubmit);
    prevPageBtn.addEventListener('click', goToPrevPage);
    nextPageBtn.addEventListener('click', goToNextPage);
    searchInput.addEventListener('input', handleSearch);
    filterSelect.addEventListener('change', handleFilterChange);
    cancelDelete.addEventListener('click', closeDeleteModal);
    confirmDelete.addEventListener('click', handleConfirmDelete);
    logoffBtn.addEventListener('click', function() {
		localStorage.removeItem('authToken');
		window.location.href = 'login.html';
	})
    // 点击模态框外部关闭
    recordModal.addEventListener('click', (e) => {
        if (e.target === recordModal) closeRecordModal();
    });
    
    deleteModal.addEventListener('click', (e) => {
        if (e.target === deleteModal) closeDeleteModal();
    });
	
	// 获取radio按钮和自定义金额容器
	const radioOptions = document.querySelectorAll('input[name="amountOption"]');
	const customAmountContainer = document.getElementById('customAmountContainer');
	const customAmountInput = document.getElementById('customAmount');
	
	// 监听radio按钮变化
	radioOptions.forEach(radio => {
		radio.addEventListener('change', () => {
			// 当选择"其他"时显示自定义输入框，否则隐藏
			if (radio.value === 'custom') {
				customAmountContainer.classList.remove('hidden');
				customAmountInput.focus();
			} else {
				customAmountContainer.classList.add('hidden');
				customAmountInput.value = '';
			}
		});
	});
    
    // 滚动时改变导航栏样式
    window.addEventListener('scroll', () => {
        const header = document.querySelector('header');
        if (window.scrollY > 10) {
            header.classList.add('py-2');
            header.classList.remove('py-3');
        } else {
            header.classList.add('py-3');
            header.classList.remove('py-2');
        }
    });
});

async function fetchRecords() {
    showLoading();
    try {
        const response = await fetch(API_GIFT, {
			headers: {
				'authToken': localStorage.getItem("authToken"),
			}
		});
		
		if (response.status === 401) {
			toLogin()
		}
		
        if (!response.ok) {
            throw new Error('获取记录失败');
        }
        records = await response.json();
        
        // 按时间倒序排序（作为后端排序的补充）
        records.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        
        renderRecords();
        updateStatistics();
        updateCharts();
    } catch (error) {
        console.error('Error fetching records:', error);
        showNotification('加载记录失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

async function createRecord(record) {
    showLoading();
    try {
        const response = await fetch(API_GIFT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
				'authToken': localStorage.getItem("authToken"),
            },
            body: JSON.stringify(record),
        });
		
		if (response.status === 401) {
			toLogin();
			return false;
		}
        
        if (!response.ok) {
            throw new Error('添加记录失败');
        }
        
        const newRecord = await response.json();
        records.unshift(newRecord);
        return true;
    } catch (error) {
        console.error('Error creating record:', error);
        showNotification('添加记录失败: ' + error.message, 'error');
        return false;
    } finally {
        hideLoading();
    }
}

function toLogin() {
	showNotification('请重新登录', 'error');
	setTimeout(() => {
		window.location.href = 'login.html';
	}, 500);
}

async function updateRecord(id, updatedData) {
    showLoading();
    try {
        const response = await fetch(`${API_GIFT}/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
				'authToken': localStorage.getItem("authToken"),
            },
            body: JSON.stringify(updatedData),
        });
		
		if (response.status === 401) {
			toLogin();
			return false;
		}
        
        if (!response.ok) {
            throw new Error('更新记录失败');
        }
        
        const updatedRecord = await response.json();
        const index = records.findIndex(r => r.id === id);
        if (index !== -1) {
            records[index] = updatedRecord;
        }
        return true;
    } catch (error) {
        console.error('Error updating record:', error);
        showNotification('更新记录失败: ' + error.message, 'error');
        return false;
    } finally {
        hideLoading();
    }
}

async function deleteRecord(id) {
    showLoading();
    try {
        const response = await fetch(`${API_GIFT}/${id}`, {
            method: 'DELETE',
			headers: {
				'authToken': localStorage.getItem("authToken"),
			},
        });
        if (response.status === 401) {
        	toLogin();
        	return false;
        }
        if (!response.ok) {
            throw new Error('删除记录失败');
        }
        
        records = records.filter(r => r.id !== id);
        return true;
    } catch (error) {
        console.error('Error deleting record:', error);
        showNotification('删除记录失败: ' + error.message, 'error');
        return false;
    } finally {
        hideLoading();
    }
}

function formatDateTime(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 显示/隐藏加载指示器
function showLoading() {
    loadingIndicator.classList.remove('hidden');
}

function hideLoading() {
    loadingIndicator.classList.add('hidden');
}

// 移动端菜单切换
function toggleMobileMenu() {
    mobileMenu.classList.toggle('hidden');
}

// 打开添加记录模态框
function openAddModal() {
	console.log("开启添加")
    document.getElementById('modalTitle').textContent = '添加礼金记录';
    recordForm.reset();
    document.getElementById('recordId').value = '';
    document.getElementById('date').valueAsDate = new Date();
    document.querySelector('input[name="type"][value="in"]').checked = true;
    recordModal.classList.remove('hidden');
    document.getElementById('name').focus();
	
	previewName.textContent = nameInput.value || '-';
	previewAmount.textContent = `¥0.00`
}

// 打开编辑记录模态框
function openEditModal(id) {
    const record = records.find(r => {
		return r.id === id
		});
    if (!record) return;
    
    currentRecordId = id;
    document.getElementById('modalTitle').textContent = '编辑礼金记录';
    document.getElementById('recordId').value = record.id;
    document.getElementById('name').value = record.name;
    document.getElementById('relationship').value = record.relationship;
    document.querySelector(`input[name="type"][value="${record.type}"]`).checked = true;
    document.getElementById('date').value = record.date;
    document.getElementById('notes').value = record.notes || '';
	
	// 金额回填逻辑
	const amount = parseFloat(record.amount); // 确保是数字类型
	const radioOptions = document.querySelectorAll('input[name="amountOption"]');
	const customAmountContainer = document.getElementById('customAmountContainer');
	const customAmountInput = document.getElementById('customAmount');
	
	// 清除所有radio选中状态
	radioOptions.forEach(radio => radio.checked = false);
	
	// 根据记录金额设置对应选项
	if (amount === 500) {
		document.querySelector('input[name="amountOption"][value="500"]').checked = true;
		customAmountContainer.classList.add('hidden');
	} else if (amount === 800) {
		document.querySelector('input[name="amountOption"][value="800"]').checked = true;
		customAmountContainer.classList.add('hidden');
	} else if (amount === 1000) {
		document.querySelector('input[name="amountOption"][value="1000"]').checked = true;
		customAmountContainer.classList.add('hidden');
	} else {
		// 非预设金额，选中"其他"并显示自定义输入框
		document.querySelector('input[name="amountOption"][value="custom"]').checked = true;
		customAmountContainer.classList.remove('hidden');
		customAmountInput.value = amount; // 回填自定义金额
	}
    
	// 更新预览
	previewName.textContent = record.name || '-';
	// 更新金额预览
	previewAmount.textContent = `¥${amount.toFixed(2)}`;
	// 更新类型预览
	updateTypePreview();
	
    recordModal.classList.remove('hidden');
    document.getElementById('name').focus();
}

// 关闭记录模态框
function closeRecordModal() {
    recordModal.classList.add('hidden');
    currentRecordId = null;
}

// 处理表单提交
async function handleFormSubmit(e) {
    e.preventDefault();
	
	// 获取选中的金额选项
	const selectedRadio = document.querySelector('input[name="amountOption"]:checked');
	const customAmountInput = document.getElementById('customAmount');
	let amount;
	
	// 验证是否选择了金额选项
	if (!selectedRadio) {
		showNotification('请选择金额', 'error');
		return;
	}
	
	// 处理金额值
	if (selectedRadio.value === 'custom') {
		// 自定义金额验证
		if (!customAmountInput.value) {
			showNotification('请输入自定义金额', 'error');
			return;
		}
		amount = parseFloat(customAmountInput.value);
	} else {
		// 预设金额
		amount = parseFloat(selectedRadio.value);
	}
	
	// 验证金额有效性
	if (isNaN(amount) || amount <= 0) {
		showNotification('请输入有效的金额', 'error');
		return;
	}
    
    const id = document.getElementById('recordId').value;
    const name = document.getElementById('name').value.trim();
    const relationship = document.getElementById('relationship').value;
    const type = document.querySelector('input[name="type"]:checked').value;
    const date = document.getElementById('date').value;
    const notes = document.getElementById('notes').value.trim();
    
    const recordData = {
        name,
        relationship,
        amount,
        type,
        date,
        notes
    };
    
    let success = false;
    
    // 编辑现有记录
    if (id) {
        success = await updateRecord(id, recordData);
        if (success) {
            showNotification('记录已更新', 'success');
        }
    } else {
        // 添加新记录
        success = await createRecord(recordData);
        if (success) {
            showNotification('记录已添加', 'success');
        }
    }
    
    if (success) {
        // 刷新界面
        renderRecords();
        updateStatistics();
        updateCharts();
        
        // 关闭模态框
        closeRecordModal();
    }
}

// 打开删除确认模态框
function openDeleteModal(id) {
    currentRecordId = id;
    deleteModal.classList.remove('hidden');
}

// 关闭删除确认模态框
function closeDeleteModal() {
    deleteModal.classList.add('hidden');
    currentRecordId = null;
}

// 处理确认删除
async function handleConfirmDelete() {
    if (!currentRecordId) return;
    
    const success = await deleteRecord(currentRecordId);
    if (success) {
        // 刷新界面
        renderRecords();
        updateStatistics();
        updateCharts();
        
        // 关闭模态框
        closeDeleteModal();
        
        // 显示通知
        showNotification('记录已删除', 'success');
    }
}

// 渲染记录列表
function renderRecords() {
    // 获取筛选和搜索后的记录
    const filteredRecords = getFilteredRecords();
    const totalPages = Math.ceil(filteredRecords.length / recordsPerPage);
    
    // 更新分页按钮状态
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
    
    // 计算当前页显示的记录范围
    const startIndex = (currentPage - 1) * recordsPerPage;
    const endIndex = Math.min(startIndex + recordsPerPage, filteredRecords.length);
    const currentRecords = filteredRecords.slice(startIndex, endIndex);
    
    // 更新显示范围文本
    showingRange.textContent = filteredRecords.length > 0 
        ? `${startIndex + 1}-${endIndex}` 
        : '0-0';
    totalCount.textContent = filteredRecords.length;
    
    // 清空表格
    recordsTableBody.innerHTML = '';
    
    // 如果没有记录
    if (currentRecords.length === 0) {
        recordsTableBody.innerHTML = `
            <tr class="text-center">
                <td colspan="6" class="px-4 py-10 text-gray-500">
                    <i class="fa fa-folder-open-o text-4xl mb-3 text-gray-300"></i>
                    <p>没有找到匹配的记录</p>
                </td>
            </tr>
        `;
        return;
    }
    
    // 添加记录到表格
    currentRecords.forEach(record => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-gray-50 transition-custom';
        
        // 格式化日期
        const date = new Date(record.date);
        const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
   //          <td class="px-4 py-4 whitespace-nowrap text-sm font-medium">
   //              <button onclick="openEditModal(${record.id})" class="text-blue-600 hover:text-blue-800 mr-3 transition-custom">
   //                  <i class="fa fa-pencil"></i> 编辑
   //              </button>
   //              <button onclick="openDeleteModal(${record.id})" class="text-red-600 hover:text-red-800 transition-custom">
   //                  <i class="fa fa-trash"></i> 删除
   //              </button>
   //          </td>
   //      `;
		
		row.innerHTML = `
		     <td class="px-4 py-4 whitespace-nowrap">${record.name}</td>
			<td class="px-4 py-4 whitespace-nowrap">${record.relationship}</td>
			<td class="px-4 py-4 whitespace-nowrap font-medium ${record.type === 'in' ? 'text-green-600' : 'text-red-600'}">
				${record.type === 'in' ? '+' : '-' }¥${record.amount.toFixed(2)}
			</td>
			<td class="px-4 py-4 whitespace-nowrap">
				<span class="px-2 py-1 text-xs rounded-full ${record.type === 'in' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
					${record.type === 'in' ? '收入' : '支出'}
				</span>
			</td>
			<td class="px-4 py-4 whitespace-nowrap text-gray-600">${formatDateTime(record.createdAt)}</td> 
		`;
        
        recordsTableBody.appendChild(row);
    });
}

// 获取筛选和搜索后的记录
function getFilteredRecords() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    const filterType = filterSelect.value;
    
    return records.filter(record => {
        // 筛选类型
        const typeMatch = filterType === 'all' || record.type === filterType;
        
        // 搜索匹配
        const searchMatch = 
            record.name.toLowerCase().includes(searchTerm) ||
            (record.notes && record.notes.toLowerCase().includes(searchTerm));
        
        return typeMatch && searchMatch;
    });
}

// 处理搜索
function handleSearch() {
    currentPage = 1;
    renderRecords();
}

// 处理筛选
function handleFilterChange() {
    currentPage = 1;
    renderRecords();
}

// 上一页
function goToPrevPage() {
    if (currentPage > 1) {
        currentPage--;
        renderRecords();
        scrollToRecords();
    }
}

// 下一页
function goToNextPage() {
    const filteredRecords = getFilteredRecords();
    const totalPages = Math.ceil(filteredRecords.length / recordsPerPage);
    
    if (currentPage < totalPages) {
        currentPage++;
        renderRecords();
        scrollToRecords();
    }
}

// 滚动到记录区域
function scrollToRecords() {
    document.getElementById('records').scrollIntoView({ behavior: 'smooth' });
}

// 更新统计信息
function updateStatistics() {
    // 总记录数
    totalRecordsEl.textContent = records.length;
    
    // 总金额
    const totalAmount = records.reduce((sum, record) => {
        return record.type === 'in' ? sum + record.amount : sum - record.amount;
    }, 0);
    totalAmountEl.textContent = `¥${totalAmount.toFixed(2)}`;
    
    // 最近更新
	if (records.length > 0) {
		const sorted = [...records].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
		lastUpdatedEl.textContent = formatDateTime(sorted[0].createdAt); // 使用格式化函数
	} else {
		lastUpdatedEl.textContent = '暂无记录';
	}
    
    // 更新关系统计
    updateRelationStats();
}

// 更新关系统计
function updateRelationStats() {
    // 按关系分组
    const relationGroups = {};
    
    records.forEach(record => {
        if (!relationGroups[record.relationship]) {
            relationGroups[record.relationship] = {
                count: 0,
                inAmount: 0,
                outAmount: 0
            };
        }
        
        relationGroups[record.relationship].count++;
        
        if (record.type === 'in') {
            relationGroups[record.relationship].inAmount += record.amount;
        } else {
            relationGroups[record.relationship].outAmount += record.amount;
        }
    });
    
    // 清空容器
    relationStats.innerHTML = '';
    
    // 如果没有数据
    if (Object.keys(relationGroups).length === 0) {
        relationStats.innerHTML = `
            <div class="col-span-full text-center py-8 text-gray-500">
                <i class="fa fa-users text-3xl mb-2 text-gray-300"></i>
                <p>暂无关系数据</p>
            </div>
        `;
        return;
    }
    
    // 添加统计卡片
    Object.entries(relationGroups).forEach(([relation, data]) => {
        const netAmount = data.inAmount - data.outAmount;
        
        const card = document.createElement('div');
        card.className = 'bg-white p-4 rounded-xl shadow-sm hover:shadow transition-custom';
        card.innerHTML = `
            <h4 class="font-medium text-gray-900 no-wrap-ellipsis">${relation}</h4>
            <p class="text-sm text-gray-500 mt-1">${data.count} 条记录</p>
            <p class="font-bold mt-2 ${netAmount >= 0 ? 'text-green-600' : 'text-red-600'} no-wrap-ellipsis">
                ${netAmount >= 0 ? '+' : ''}¥${netAmount.toFixed(2)}
            </p>
            <div class="flex justify-between text-xs mt-2">
                <span class="text-green-600 no-wrap-ellipsis">收入: ¥${data.inAmount.toFixed(2)}</span>
                <span class="text-red-600 no-wrap-ellipsis">支出: ¥${data.outAmount.toFixed(2)}</span>
            </div>
        `;
        
        relationStats.appendChild(card);
    });
}

// 初始化图表
function initCharts() {
    // 趋势图表
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    trendChart = new Chart(trendCtx, {
        type: 'line',
        data: getTrendChartData(),
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value;
                        }
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
    
    // 饼图
    const pieCtx = document.getElementById('pieChart').getContext('2d');
    pieChart = new Chart(pieCtx, {
        type: 'doughnut',
        data: getPieChartData(),
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                            return `${label}: ¥${value.toFixed(2)} (${percentage}%)`;
                        }
                    }
                }
            },
            cutout: '65%',
            animation: {
                animateRotate: true,
                animateScale: true,
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 更新图表数据
function updateCharts() {
    if (trendChart) {
        trendChart.data = getTrendChartData();
        trendChart.update();
    }
    
    if (pieChart) {
        pieChart.data = getPieChartData();
        pieChart.update();
    }
}

// 获取趋势图表数据
function getTrendChartData() {
    // 按日期分组数据
    const dateGroups = {};
    
    // 获取最近30天的日期
    const today = new Date();
    for (let i = 29; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(today.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        dateGroups[dateStr] = { in: 0, out: 0 };
    }
    
    // 累加数据
    records.forEach(record => {
        const dateStr = record.date;
        if (dateGroups[dateStr]) {
            if (record.type === 'in') {
                dateGroups[dateStr].in += record.amount;
            } else {
                dateGroups[dateStr].out += record.amount;
            }
        }
    });
    
    // 准备图表数据
    const labels = Object.keys(dateGroups);
    const inData = labels.map(date => dateGroups[date].in);
    const outData = labels.map(date => dateGroups[date].out);
    
    return {
        labels: labels,
        datasets: [
            {
                label: '收入',
                data: inData,
                borderColor: '#10B981',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                fill: true,
                tension: 0.4
            },
            {
                label: '支出',
                data: outData,
                borderColor: '#EF4444',
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                fill: true,
                tension: 0.4
            }
        ]
    };
}

// 获取饼图数据
function getPieChartData() {
    // 计算总收入和总支出
    const totals = records.reduce((acc, record) => {
        if (record.type === 'in') {
            acc.in += record.amount;
        } else {
            acc.out += record.amount;
        }
        return acc;
    }, { in: 0, out: 0 });
    
    return {
        labels: ['收入', '支出'],
        datasets: [{
            data: [totals.in, totals.out],
            backgroundColor: [
                '#10B981',
                '#EF4444'
            ],
            borderColor: [
                '#10B981',
                '#EF4444'
            ],
            borderWidth: 1
        }]
    };
}

// 显示通知
function showNotification(message, type = 'success') {
    notificationMessage.textContent = message;
    
    if (type === 'success') {
        notificationIcon.className = 'fa fa-check-circle mr-2';
        notification.classList.remove('bg-red-600');
        notification.classList.add('bg-green-600');
    } else if (type === 'error') {
        notificationIcon.className = 'fa fa-times-circle mr-2';
        notification.classList.remove('bg-green-600');
        notification.classList.add('bg-red-600');
    }
    
    // 显示通知
    notification.classList.remove('translate-y-20', 'opacity-0');
    notification.classList.add('translate-y-0', 'opacity-100');
    
    // 3秒后隐藏
    setTimeout(() => {
        notification.classList.remove('translate-y-0', 'opacity-100');
        notification.classList.add('translate-y-20', 'opacity-0');
    }, 3000);
}

// 暴露函数到全局，以便在HTML中调用
window.openEditModal = openEditModal;
window.openDeleteModal = openDeleteModal;
    